Simple analysis of the conversion between string and char* char[]

  • 2020-04-02 01:47:19
  • OfStack

1. First, it is important to understand that a string can be thought of as a container with characters as elements. Characters form a sequence (string). Sometimes traversing in a sequence of characters, the standard string class provides an STL container interface. There are member functions such as begin() and end() that the iterator can locate based on.

Note that unlike char*, a string does not necessarily end with NULL('\0'). The string length can be obtained by length(), and the string can be accessed by subscripts. Therefore, you cannot assign a string directly to a char star.

2. Convert string to char *

If you want to convert a string directly to const char * type. String has two functions that you can use.

One is. C_str (), and one is a data member function.

Here are some examples:

String s1 = "abcdeg";
Const char *k = s1.c_str();
Const char *t = s1.data();
Printf (" % s % s ", k, t);
cout < < K. < < t < < Endl;

As above, both can be output. The content is the same. However, only const char* can be converted to const, if the const compilation cannot be passed without const.

So, if you want to convert to a char star, you can implement it as a member of string, copy.

String s1 = "abcdefg";
Char * data;
Int len = s1. The length ();
Data = (char *) malloc (len (+ 1) * sizeof (char));
S1. Copy (data, len, 0).
Printf (" % s ", data);
cout < < The data;

3, char * to string

You can assign it directly.

String s;

Char * p = "adghrtyh";

S = p;

But this is going to be a problem.

There's a situation that I want to explain. When we define a string type, we use printf("%s",s1); The output is going to go wrong. This is because "%s" requires the first address of the following object. But string is not such a type. So something must be wrong.

There is no problem with cout output, if you must printf output. Here's how:
Printf (" % s ", s1 c_str ())

Char [] to string

This one can also be assigned directly. But there are also problems. You need the same treatment.

5. String to char[]

Because we know the length of the string, we can get it from the length() function, and we can access it directly from the index, so we can assign it in a loop.

Such a transformation cannot be directly assigned.

      String pp = "dagah";
      Char p [8];
      Int I;
      For (I = 0; i. < Pp. Length (); I++)
              P = pp [I] [I];
      P [I] = '\ 0';
      Printf (" % s \ n ", p);
      cout < < P;


Related articles: